package com.example.systemserver.service;

import cn.hutool.core.util.IdUtil;
import com.example.systemserver.bean.RequestBean;
import com.example.systemserver.config.MyException;
import com.example.systemserver.mapper.PersonMapper;
import com.example.systemserver.bean.PersonBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class PersonService {

    @Resource
    private PersonMapper personMapper;

    public void save(PersonBean personBean) {
        log.debug("学员保存,检查参数");
        if (personBean == null) {
            throw new MyException("参数不能为空");
        }
        if (personBean.getTitle() == null || personBean.getTitle().trim().isEmpty()) {
            throw new MyException("姓名不能为空");
        }
        if (personBean.getAge() == null || personBean.getAge() <= 0) {
            throw new MyException("年龄不能小于0");
        }
        if (personBean.getGender() == null || personBean.getGender().trim().isEmpty()) {
            throw new MyException("性别不能为空");
        }

        log.debug("学员保存,保存数据");
        int updated ;
        if (personBean.getId()== null){
            log.debug("学员保存,新增数据");
            personBean.setId(IdUtil.getSnowflakeNextId());
            personBean.setCreatedTime(System.currentTimeMillis());
            personBean.setUpdatedTime(System.currentTimeMillis());

            updated = personMapper.save(personBean);
        }else{
            log.debug("学员保存,修改数据");
            personBean.setUpdatedTime(System.currentTimeMillis());
            updated = personMapper.edit(personBean);
        }
        if (updated <= 0){
            throw new MyException("保存失败");
        }
    }

    public void remove(PersonBean personBean) {
        log.debug("学员删除,检查参数");
        if (personBean == null|| personBean.getId() == null){
            throw new MyException("参数不能为空");
        }
        log.debug("学员删除,执行sql");
        int updated = personMapper.remove(personBean);
        if (updated <= 0){
            throw new MyException("删除失败");
        }
    }

    public PageInfo<PersonBean> list(RequestBean<PersonBean> requestBean) {
        log.debug("学员列表,设置分页");
        PageHelper.startPage(requestBean.getPageNum(),requestBean.getPageSize());
        log.debug("学员列表,执行sql");
        //从RequestBean中获取查询条件
        PersonBean params = requestBean.getParams();
        List<PersonBean> list = personMapper.list(params);
        return new PageInfo<>(list);
    }

    public PersonBean info(PersonBean personBean) {
        log.debug("学员详情,检查参数");
        if (personBean == null|| personBean.getId() == null){
            return  null;
        }
        log.debug("学员详情,执行sql");
        return personMapper.info(personBean);
    }

}
